package Entities 
{
	import flash.display.Graphics;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import screens.NoteCanvas;
	/**
	 * ...
	 * @author Andy Wolff
	 */
	public class InstrumentLayer
	{
		public var visible:Boolean=true;
		public var color:uint;
		public var type:int;
		private var notes:Array;
		public function getNotes():Array { return notes; }
		private var view:NoteCanvas;
		public function InstrumentLayer(view:NoteCanvas, color:uint, type:int) 
		{
			this.view = view;
			this.color = color;
			this.type = type;
			notes = new Array();
		}
		
		public function draw(g:Graphics):void {
			if (!visible) return;
			var bounds:Rectangle = view.getPlayArea();
			if (notes!=null) for each (var note:Note in notes) if (note!=null) note.draw(g,bounds);
		}
		
		public function addNote(n:Note):void {
			notes.push(n);
		}
		public function removeNote(n:Note):void {
			notes.splice(notes.indexOf(n), 1);
		}
		
		public function mergeInstrument(instrument:InstrumentLayer):void {
			instrument.unify();
			for each (var note:Note in instrument.getNotes()) {
				//add the note in to this instrument
				addNote(new Note(this,note.getWhich(),note.getStart(),note.getEnd()));
			}
			unify();
		}
		
		public function subtractInstrument(instrument:InstrumentLayer):void {
			instrument.unify();
			for each (var note:Note in instrument.getNotes()) {
				//subtract the note from this instrument
				for (var i:int = 0; i < notes.length; i++) { if (notes[i] != null && notes[i].subtract(note)) i--; }
			}
			unify();
		}
		
		public function unify():void {
			//try to unify all existing notes
			for (var i:int = 0; i <= notes.length; i++) {
				for (var ii:int = 0; ii <= notes.length; ii++) {
					if (notes[i] != null && notes[ii]!=null && notes[i].unify(notes[ii])) ii--;
				}
			}
		}
		
		public function getNoteAtPosition(p:Point):Note {
			p.x = NoteCanvas.getNoteX(p.x);
			p.y = NoteCanvas.getNoteRow(p.y);
			//trace(p.x + "," + p.y);
			for each (var note:Note in notes) { if (note.getWhich() == p.y && p.x >= note.getStart() && p.x <= note.getEnd()) { /*trace(note);*/ return note; }}
			return null;
		}
	}

}